var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

// 引入数据库,进行数据库链接
require('./connfig/db.config')
// 引入JWT验证
var JWT =  require('./util/JWT')

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
const UserRouter = require('./routes/admin/UserRouter');
const HotRouter = require('./routes/admin/HotRouter');
const ProductRouter = require('./routes/admin/ProductRouter');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));



// 应用级中间件-验证token是否失效
app.use((req,res,next)=>{
  // 如果token有效,next()放行
  // token失效,返回401无权限
  if(req.url === '/adminapi/user/login'){
    next()
  }else{
    // 如果不是登录请求,就查看请求头是否有携带token
  const token = req.headers["authorization"].split(" ")[1]
  // 有token就再次进行生成新的 token (每次请求 生成新的token,实效期限从头开始计算)
  if(token){
    const payload =  JWT.verify(token)
    console.log(payload); //↓若token失效,返回的是false (具体业务逻辑在 JWT.js文件)
    if(payload){  
      const newToken=  JWT.generate({
        _id : payload._id,
        username: payload.username
      },'.5h')
      // 响应头设置Authorization新的 token 
      res.header('Authorization', newToken)
        
      next()
    }else{
      res.status(401).send({
        errCode:'-1',
        errorInfo:'token已过期'
      })
    }
  }
  }

})



app.use('/', indexRouter);
app.use('/users', usersRouter);

// /adminapi/  后台系统使用
app.use(UserRouter)
app.use(HotRouter) 
app.use(ProductRouter) 
// /webapi/   企业官网使用


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
